package com.activities;


import java.util.Arrays;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TableRow;
import com.Adapters.FollowersAdapter;
import com.Animations.AnimUtil;
import com.Data.Followers;
import com.Data.Followers.onGetFollowersCompleted;
import com.Data.User;
import com.Managers.ConnectionManagerClass;
import com.Managers.FragmentManagerClass;
import com.Managers.UserManagerClass;
import com.PopUps.PopUpClass;
import com.TextFormat.UtilFonts;
import com.shareup.R;


public class FragmentFollower extends Fragment {

    public static void delayTask(final Followers fl, final int time) {

        Handler myHandler = new Handler();
        myHandler.postDelayed(new Runnable() {

            @Override
            public void run() {

                fl.execute(Followers.ACTION_GET);
            }
            //
        }, time);
    }

    public boolean followChanged;

    private FollowersAdapter adapter;

    private ListView list;

    private boolean loaded;

    private RelativeLayout mainLay;

    private View pview;

    private EditText searchText;

    private TableRow table;

    private final TextWatcher textChanged = new TextWatcher() {

        @Override
        public void afterTextChanged(Editable s) {

            // TODO Auto-generated method stub
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

            followChanged = false;
            //
            if (searchText.getText().length() > 2) {
                wasSearching = true;
                findFollowers(searchText.getText().toString());
            }
            else
                if (searchText.getText().length() == 0) {
                    wasSearching = false;
                    loadFollows();
                }
        }
    };

    private boolean wasSearching;

    public void addFriendsToList(User[] result) {

        if (result != null && result.length > 0) {
            // ORDERING THE LIST
            Arrays.sort(result, User.UserComparator);
            //
            boolean updated = false;
            //
            for (int i = 0; i < result.length; i++) {
                if (!containsFollower(result[i].getID())) {
                    adapter.add(result[i]);
                    updated = true;
                }

            }
            if (updated)
                adapter.notifyDataSetChanged();

            if (wasSearching)
                wasSearching = false;

            this.setLoadingCompleted();
        }
        else {
            // SIN SEGUIDORES
            // clearAll();
            //
            table.removeAllViews();
            PopUpClass up = new PopUpClass(getActivity());
            //
            up.setMessage(getActivity().getResources().getString(R.string.dialog_no_followers), R.drawable.follow_add_icon_pressed, table);
            AnimUtil.animatePopUp(table, true, null);
            //

        }

    }

    public void addList() {

        if (!mainLay.getChildAt(0).equals(list)) {
            mainLay.addView(list, 0);
        }
    }

    public void clearAll() {

        searchText.setText("");
        adapter.clear();
        this.list.setAdapter(null);

    }

    public void loadFollows() {

        if (ConnectionManagerClass.isConnection(getActivity())) {

            setLoading();

            if (list.getAdapter() == null)
                list.setAdapter(adapter);

            Followers fl = new Followers(UserManagerClass.UserLogged.getID());
            fl.setCallbackGetFollowers(new onGetFollowersCompleted() {

                @Override
                public void Completed(User[] result) {

                    adapter.clear();
                    adapter.notifyDataSetChanged();

                    addFriendsToList(result);

                }
            });
            delayTask(fl, 1000);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        pview = inflater.inflate(R.layout.activity_followers, null);
        FragmentManagerClass.aFollow = this;

        inicializar();

        return pview;
    }

    public void removeList() {

        mainLay.removeView(list);
    }

    public void setBackConnection() {

        addList();
        AnimUtil.animatePopUp(table, false, null);
    }

    public void setLoading() {

        if (table.getChildCount() > 0) {
            table.removeAllViews();
        }
        PopUpClass pc = new PopUpClass(getActivity());
        pc.setLoadingList(table);

    }

    public void setLoadingCompleted() {

        AnimUtil.animatePopUp(table, false, null);
    }

    public void setNotConnection(String message) {

        removeList();

        PopUpClass pc = new PopUpClass(getActivity());
        pc.setMessage(message, R.drawable.connection_error, table);
    }

    private boolean containsFollower(int id) {

        for (int i = 0; i < adapter.getCount(); i++) {
            if (id == adapter.getItemId(i)) {
                return true;
            }
        }
        return false;
    }

    private void findFollowers(String name) {

        adapter.clear();
        adapter.notifyDataSetChanged();

        Followers fl = new Followers(name);
        fl.setCallbackGetFollowers(new onGetFollowersCompleted() {

            @Override
            public void Completed(User[] result) {

                addFriendsToList(result);

            }
        });
        fl.execute(Followers.ACTION_SEARCH);

    }

    private void inicializar() {

        if (!loaded) {
            list = (ListView) pview.findViewById(R.id.follower_listview);
            mainLay = (RelativeLayout) pview.findViewById(R.id.activity_followers_layout);
            adapter = new FollowersAdapter(this.getActivity(), R.layout.item_follower, R.id.f_text_name);
            list.setAdapter(adapter);
            searchText = (EditText) pview.findViewById(R.id.afollowers_search_text);
            UtilFonts.setTextRegularFont(searchText);
            searchText.addTextChangedListener(textChanged);

            table = (TableRow) pview.findViewById(R.id.aFollower_table_tooltip);
            loaded = true;
        }

    }
}
